import React, { useEffect, useRef } from 'react'

import PropTypes from 'prop-types'

import styles from './index.module.css'

export default function Sticky(props) {
  // 创建 ref 对象
  const placeholder = useRef()
  const content = useRef()

  // 监听 scroll 事件
  useEffect(() => {
    // 监听 scroll 事件
    const handleScroll = () => {
      const placeholderEl = placeholder.current
      const contentEl = content.current

      const { top } = placeholderEl.getBoundingClientRect()
      if (top < 0) {
        // 吸顶
        contentEl.classList.add(styles.fixed)
        placeholderEl.style.height = `${props.height}px`
      } else {
        // 非吸顶
        contentEl.classList.remove(styles.fixed)
        placeholderEl.style.height = '0px'
      }
    }

    window.addEventListener('scroll', handleScroll)

    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [props.height])

  return (
    <div>
      {/* 占位元素 */}
      <div ref={placeholder} />
      {/* 内容元素 */}
      <div ref={content}>{props.children}</div>
    </div>
  )
}

Sticky.propTypes = {
  height: PropTypes.number.isRequired
}
